import React, { useEffect, useState } from 'react';
import { Button, ButtonGroup, Container, Dropdown, DropdownButton, Form } from 'react-bootstrap';
import appSetting from '../../store/AppSetting';
import './menu.css'
interface MenuSubButtonInfo{
    list:Array<MenuButton>
}

interface MenuButton{
  name:string;
  type?:string;
  value?:string;
  url?:string;
  key?:string;
  appid?:string;
  media_id?:string;
  pagepath?:string;
  article_id?:string;
  sub_button?:MenuSubButtonInfo
}

interface MenuDetail{
    button:Array<MenuButton>
}

interface MenuModel{
    is_menu_open:number;
    selfmenu_info:MenuDetail
}

const Menu:React.FC = ()=>{
    
    const types = [
        'click',
        'view',
        'scancode_push',
        'scancode_waitmsg',
        'pic_sysphoto',
        'pic_photo_or_album',
        'pic_weixin',
        'location_select',
        'media_id',
        'article_id',
        'article_view_limited',
        'sub_button'
    ];

    const [menuInfo,setMenuInfo] = useState<MenuDetail>();
    const [isEdit,setIsEdit] = useState(false);
    const [draft,setDraft] = useState<MenuDetail>();
    const [currentBtn,setCurrentBtn] = useState<MenuButton>();
    const [currentSubBtn, setCurrentSubBtn] = useState<MenuButton>();
    const [draftJson,setDraftJson] = useState<string>("");

    useEffect(()=>{
        fetch(`/wxproxy/cgi-bin/get_current_selfmenu_info?access_token=${appSetting.accessToken}`)
        .then((res)=>res.json())
        .then((resp:MenuModel)=>{
            if(!resp.selfmenu_info){
                alert(JSON.stringify(resp));
            }
            setMenuInfo(resp.selfmenu_info)
            setDraft(JSON.parse(JSON.stringify(resp.selfmenu_info)));
            setDraftJson(JSON.stringify(resp.selfmenu_info));
        })
    },[])


    const renderButtonEditArea = (btn?:MenuButton,isSubBtn:boolean=true)=> {
        return (<Container>
                    <p>当前按钮名:&nbsp;{(isSubBtn ? currentSubBtn?.name : currentBtn?.name)||"--"}</p>
                    <Form.Control type='input' defaultValue={isSubBtn ? currentSubBtn?.name : currentBtn?.name}
                    placeholder={(isSubBtn ? currentSubBtn?.name : currentBtn?.name)||"请输入按钮标题"}
                    onChange={(e)=>{
                        if(!isSubBtn && currentBtn != null){
                            currentBtn.name = e.currentTarget.value;
                            setCurrentBtn(currentBtn);
                        }else if(isSubBtn && btn != null){
                            btn.name = e.currentTarget.value;   
                            setCurrentSubBtn(btn)                     
                        }
                        setDraftJson(JSON.stringify(draft))
                    }}/>
                    {btn?.type === 'click' ?<>
                    <p>Key</p>
                    <Form.Control type='input' defaultValue={btn.key} placeholder='后台key值' onChange={(e)=>{
                        btn.key = e.currentTarget.value||"";
                        setDraftJson(JSON.stringify(draft))
                    }}></Form.Control>
                    </> :null}
                    {btn?.type === 'view'||btn?.type==='miniprogram' ?<>
                    <p>Url</p>
                    <Form.Control type='input' defaultValue={btn.url} placeholder='跳转链接' onChange={(e)=>{
                        btn.url = e.currentTarget.value||"";
                        setDraftJson(JSON.stringify(draft))
                    }}></Form.Control>
                    </> :null}
                    {btn?.type === 'media_id'||btn?.type==='view_limited' ?<>
                    <p>media_id</p>
                    <Form.Control type='input' defaultValue={btn.url} placeholder='素材media_id' onChange={(e)=>{
                        btn.url = e.currentTarget.value||"";
                        setDraftJson(JSON.stringify(draft))
                    }}></Form.Control>
                    </> :null}
                    {btn?.type === 'miniprogram' ?<>
                    <p>appid</p>
                    <Form.Control type='input' defaultValue={btn.appid} placeholder='小程序appid' onChange={(e)=>{
                        btn.appid = e.currentTarget.value||"";
                        setDraftJson(JSON.stringify(draft))
                    }}></Form.Control>
                    </> :null}
                    {btn?.type === 'miniprogram' ?<>
                    <p>pagepath</p>
                    <Form.Control type='input' defaultValue={btn.pagepath} placeholder='小程序pagepath' onChange={(e)=>{
                        btn.pagepath = e.currentTarget.value||"";
                        setDraftJson(JSON.stringify(draft))
                    }}></Form.Control>
                    </> :null}
                    {btn?.type === 'article_id' || btn?.type === 'article_view_limited' ?<>
                    <p>article_id</p>
                    <Form.Control type='input' defaultValue={btn.article_id} placeholder='article_id' onChange={(e)=>{
                        btn.article_id = e.currentTarget.value||"";
                        setDraftJson(JSON.stringify(draft))
                    }}></Form.Control>
                    </> :null}
                    <p>当前按钮类型:&nbsp;{(isSubBtn ? currentSubBtn?.type : currentBtn?.type)||(isSubBtn? "--":"sub_button")}</p>
                  {<DropdownButton 
                as={ButtonGroup}
                id={'menutype'}
                title={(isSubBtn ? currentSubBtn?.type : currentBtn?.type)||(isSubBtn? "--":"sub_button")}
                style={{padding:10}}
                onSelect={(eventKey)=>{
                    if(!isSubBtn && currentBtn != null) {
                        currentBtn.type = eventKey||"click";
                        if(currentBtn.type !== 'sub_button'){
                            delete currentBtn.sub_button;
                            setCurrentSubBtn(undefined);
                        }else if(!currentBtn.sub_button){
                            currentBtn.sub_button = {list:[]};
                        }
                        setCurrentBtn(currentBtn);
                    }else if(isSubBtn && btn != null){
                        btn.type = eventKey||'click';
                        setCurrentSubBtn(btn)
                    }
                    setDraftJson(JSON.stringify(draft))
                }}
                >
                {types.filter((t)=> {
                    if(isSubBtn){
                        return t!=='sub_button';
                    }else{
                        return true;
                    }
                }).map((type,index)=>{
                    return (<Dropdown.Item 
                        key={type+index}
                        eventKey={type}
                    >
                        {type}
                    </Dropdown.Item>)
                })}
            </DropdownButton>}
        </Container>);
    }

    return (<Container style={{padding:20,paddingBottom:50}}>
        <h1>当前生效菜单</h1>
        {!isEdit && <Container>
        { menuInfo?.button.map((menu,idx)=>{
            return (menu.sub_button ? <DropdownButton 
            as={ButtonGroup}
            key={'primary'+idx}
            id={'menu'+idx.toString()}
            title={menu.name}
            >
                {menu.sub_button?.list.map((sbtn,index)=>{
                    return (<Dropdown.Item eventKey={sbtn.key}>{sbtn.name}</Dropdown.Item>)
                })}
            </DropdownButton>:<Button>{menu.name}</Button>)
        })}
        </Container>}
        {isEdit &&(
        <Container>
            <h3>请先选中灰色按钮再编辑</h3>
            <Container style={{marginTop:20,display:"flex",flexDirection:"row"}}>
                {draft && draft?.button.map((btn,idx)=>{
                    // 主菜单按钮
                return (<Button 
                    variant={'secondary'}
                    id={'menu'+idx.toString()}
                    onClick={()=>{
                        setCurrentBtn(btn)
                        setDraftJson(JSON.stringify(draft))
                    }}
                    >{btn.name}</Button>)
            })}
            &nbsp;&nbsp;&nbsp;
            <Button onClick={()=>{
                if(draft && draft.button && draft?.button.length > 2){
                    alert('主菜单按钮不能超过3个')
                }else{
                    
                }
            }}>添加主菜单按钮</Button>
        </Container>
        <Container style={{marginTop:20,borderWidth:1,borderStyle:"dashed"}}>
               {currentBtn ? <Container style={{display:"flex",flexDirection:'column'}}>
                <p>菜单编辑区域 </p>
                <Container style={{display:"flex",flexDirection:"row",alignItems:"center"}}>
                    {renderButtonEditArea(currentBtn,false)}
                </Container>
               {currentBtn.type === 'sub_button' || !currentBtn.type ?  (<Container>
                    <p>子菜单</p>
                    <Container style={{display:"flex",flexDirection:"row"}}>
                    <Container style={{display:'flex',flex:1,flexDirection:"column"}}>
                        {currentBtn?.sub_button && currentBtn.sub_button.list.length > 0 ? currentBtn.sub_button.list.map((btn,idx)=>{
                            // 子菜单按钮
                            return <Button variant='info' onClick={()=>{
                                setCurrentSubBtn(btn);
                            }}>{btn.name}</Button>
                        }):null}
                        {!currentBtn?.sub_button?.list || currentBtn.sub_button.list.length < 5 ? <Button onClick={()=>{
                            var subBtn = {} as MenuButton;
                            currentBtn?.sub_button?.list.push(subBtn)
                            setCurrentSubBtn(subBtn);
                        }}>添加菜单</Button>:null}
                    </Container>
                    <Container style={{display:'flex',flex:1,flexDirection:"column"}}>
                        {renderButtonEditArea(currentSubBtn,true)}
                    </Container>
                    </Container>
                </Container>) : (<Container>
                {/* {renderButtonEditArea(currentBtn,false)} */}
               </Container>)}
        </Container>:null} 
        </Container>
        <p>预览 &nbsp; &nbsp;</p>
        {draft && draft?.button.map((menu,idx)=>{
            return (menu.sub_button ? <DropdownButton 
            as={ButtonGroup}
            variant={'outline-info'}
            id={'menu'+idx.toString()}
            title={menu.name}
            >
                {menu.sub_button?.list.map((sbtn,index)=>{
                    return (<Dropdown.Item eventKey={sbtn.key}>{sbtn.name}</Dropdown.Item>)
                })}
            </DropdownButton>:<Button>{menu.name}</Button>)
        })}
        <p>{draftJson}</p>
        </Container>)}
        <Container>
            <h3>个性化(matchrule)</h3>
            <p>tag_id</p><Form.Control></Form.Control>
            <p>client_platform_type</p><Form.Control></Form.Control>
        </Container>
        <Container style={{marginTop:20}}>
            <ButtonGroup>
                <Button variant='outline-info' onClick={()=>{
                    setIsEdit(!isEdit);
                    let copiedDraft = JSON.parse(JSON.stringify(menuInfo));
                    setDraft(copiedDraft);
                }}>{isEdit ? "取消编辑":"编辑"}</Button>
                <Button onClick={()=>{
                    setIsEdit(false);
                    let uploadBtn:MenuDetail = JSON.parse(draftJson) as MenuDetail;
                    let btns = [];
                    for(let i=0; i< uploadBtn.button.length; i++){
                        let btn = uploadBtn.button[i];
                        let tbtn = Object.assign({},btn) as any;
                        if(btn.sub_button && btn.sub_button.list && btn.sub_button.list.length > 0){
                            tbtn.sub_button = btn.sub_button.list;
                        }else{
                            delete tbtn.sub_button;
                        }
                        btns.push(tbtn);
                    } 

                    let jsonStr = JSON.stringify({"button":btns});
                    console.log("updated btn json: "+jsonStr);
                    //提交保存
                    fetch(`/wxproxy/cgi-bin/menu/create?access_token=${appSetting.accessToken}`,
                    {
                     method:"POST",
                     body:jsonStr
                    })
                    .then(res=>res.json())
                    .then((resp)=>{
                        alert(JSON.stringify(resp));
                        console.log("got response: "+JSON.stringify(resp));
                    }).catch((err)=>{
                        alert("save failed");
                    })
                }}>保存</Button>
            </ButtonGroup>
        </Container>
    </Container>);
}

export default Menu;